package com.ctshk.rpc.payment.utils.mastercard;

import com.ctshk.rpc.payment.dto.rep.mastercard.HostedSession;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author hef
 */
public class ApiResponseService {

    private static final Logger logger = LoggerFactory.getLogger(ApiResponseService.class);

    /**
     * Parses JSON response from session-based API call into HostedSession object
     *
     * @param sessionResponse response from API
     * @return HostedSession
     */
    public static HostedSession parseSessionResponse(String sessionResponse) {
        try {
            JsonObject json = new Gson().fromJson(sessionResponse, JsonObject.class);
            JsonObject jsonSession = json.get("session").getAsJsonObject();

            HostedSession hostedSession = new HostedSession();
            hostedSession.setId(jsonSession.get("id").getAsString());
            hostedSession.setVersion(jsonSession.get("version").getAsString());
            if (json.get("successIndicator") != null)
                hostedSession.setSuccessIndicator(json.get("successIndicator").getAsString());

            return hostedSession;
        } catch (Exception e) {
            logger.error("Unable to parse session response", e);
            throw e;
        }
    }
}
